# -*-coding:utf-8 -*-
import bluetooth
import re
import time

class blueAPI:
	#y p r
	res = [0.0, 0.0, 0.0]

	#param
	addr = "98:D3:36:80:FE:8C"
	#addr = "98:D3:37:90:F0:08"
	#addr = "CC:44:63:54:FD:7D"
	port = 1
	sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
	status = False
	cutDown = False

	def isconnect(self):
		return self.status

	#connect
	def connect(self):
		try:
			self.sock.connect((self.addr, self.port))
			self.status = True
			print ("Connect success")
			return True
		except IOError as e:
			self.status = False
			print("连接失败，请重试……")
			print("[INFO] ", e)
			return False

	def keepConnect(self):
		try:
			while True:
				data = self.getData()
				time.sleep(1)
				#print("\r[INFO] Current Data:", data, end="")
				if self.cutDown:
					break
			print("[INFO] 暂停读取蓝牙数据...")
		except IOError as e:
			print("Error accur")

	def validJudge(self, x):
		pattern = re.compile(r"^y=(-)*\d+\.\d\s+p=(-)*\d+\.\d\s+r=(-)*\d+\.\d$")
		if pattern.match(x):
			return True
		else:
			return False

	def getData(self):
		while(1):
			#print("Trying to get data...")
			try:
				x = self.sock.recv(35).decode()
			except OSError as e:
				print("[INFO] 蓝牙无数据！")
				break
			x = x.replace('\r','').replace('\n','')
			if self.validJudge(x):
				lines = x.split("\t ")
				self.res[0] = float(lines[0].split("=")[1])	#yaw
				self.res[1] = float(lines[1].split("=")[1])	#pitch
				self.res[2] = float(lines[2].split("=")[1])	#roll
				#print("y:",self.res[0], "\tr:", self.res[1], "\tp:", self.res[2])
				return self.res
				
if __name__ == '__main__':
	blue = blueAPI()
	blue.connect()
	print("连接完成")
	while True:
		data = blue.getData()
		print(data)
